import OpenAI from 'openai';
import healthDataService from './healthData.js';
import sleepDataService from './sleepData.js';
import activityDataService from './activityData.js';
import User from '../models/user.js';// example data
import Medication from '../models/medication.js';// example data
import MedicalRecord from '../models/medicalRecord.js';// example data

const openai = new OpenAI({
    // 若没有配置环境变量，请用百炼API Key将下行替换为：apiKey: "sk-xxx",
    apiKey: process.env.DASHSCOPE_API_KEY,
    baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
});


const reportPrompt = ``;

const AI = {
    async AIParseData(userId, userPrompt) {
        try {
            const { name, age, sex } = await User.findByPk(userId);


            
            // 获取最新的一条健康数据
            const heartRateData = await healthDataService.getStatistics(
                userId,
                'week',
                'heartRate',
            );
            const bloodPressureData = await healthDataService.getStatistics(
                userId,
                'week',
                'bloodPressure',
            );
            const bloodOxygenData = await healthDataService.getStatistics(
                userId,
                'week',
                'bloodOxygen',
            );

            const sleepData = await sleepDataService.getSleepStatistics(userId, 'week');
            const activityData = await activityDataService.getActivityStatistics(userId, 'week');

            const medications = await Medication.findAll({
                where: { userId: userId },
            });

            const medicalRecords = await MedicalRecord.findAll({
                where: { userId: userId },
            });

            const Data = {
                userInfo: {
                    name: name,
                    age: age,
                    sex: sex,
                },
                healthData: {
                    bloodPressureData: bloodPressureData.data,
                    bloodOxygenData: bloodOxygenData.data,
                    heartRateData: heartRateData.data,
                    sleepData: sleepData.data,
                    activityData: activityData.data,
                    medications: medications,
                    medicalRecords: medicalRecords,
                },
            };

            const parsePrompt = `你是一位专注于老年人身体健康的智能助理,你的主要职责是根据用户的健康数据进行分析和健康评估,并且提供健康建议,同时结合用户输入回答用户的健康问题,要注意回答要通俗易懂,适合老年人,接下来是用户的健康数据:${ JSON.stringify(Data) } .`;


            const completion = await openai.chat.completions.create({
                model: 'qwen-plus-latest', //此处以qwen-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                messages: [
                    { role: 'system', content: parsePrompt },
                    { role: 'user', content: userPrompt },
                ],
            });

            // 👇 打印原始响应（可选）
            console.log('Raw response:', JSON.stringify(completion, null, 2));

            // 👇 提取 content 字符串
            const rawContent = completion.choices[0].message.content;

            // // 👇 去除 Markdown 代码块标记
            // const jsonString = rawContent.replace(/```json\n?/g, '').replace(/```/g, '');

            // // 👇 解析 JSON 字符串
            // const parsedResult = JSON.parse(jsonString);


            // 👇 输出结果
            // console.log("给医生的建议:", doctorAdvice);
            // console.log("给患者的建议:", patientAdvice);

            return rawContent;
        } catch (error) {
            console.error('分析失败:', error);
            return null;
        }
    },

    // async AIMakeReport(userId, period) {
    //     let HealthData;
    //     try {
    //         if (period == 'weekly' || period == 'monthly') {
    //             HealthData = await HealthDataService.getHealthDataByUserId(userId, period);
    //         } else {
    //             throw new Error('Invalid period');
    //         }

    //         const completion = await openai.chat.completions.create({
    //             //此处以qwen-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
    //             model: 'qwen-plus',
    //             messages: [
    //                 { role: 'system', content: reportPrompt },
    //                 { role: 'user', content: JSON.stringify(HealthData) },
    //             ],
    //         });

    //         console.log('Raw response:', JSON.stringify(completion, null, 2));

    //         // 👇 提取 content 字符串
    //         const rawContent = completion.choices[0].message.content;

    //         // 👇 去除 Markdown 代码块标记
    //         const jsonString = rawContent.replace(/```json\n?/g, '').replace(/```/g, '');

    //         const jsonData = JSON.parse(jsonString);
    //     } catch (error) {}
    // },
};

export default AI;
